package com.simafei.flow.core;

import cn.hutool.core.collection.CollectionUtil;
import com.simafei.flow.core.common.ExecStatus;
import com.simafei.flow.core.common.NodeType;
import com.simafei.flow.core.common.Variable;
import lombok.EqualsAndHashCode;
import lombok.Setter;
import lombok.ToString;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author fengpengju
 */
@EqualsAndHashCode(callSuper = true)
@ToString
@Setter
public class EndNode extends Node {

    /**
     * 输出字段
     */
    private List<Variable> outVars;

    public EndNode() {
        super(NodeType.END);
    }

    @Override
    protected List<ExecutionResult> doExecute(ExecutionContext context, List<Map<String, Object>> params) {
        context.setExecStatus(ExecStatus.FINISHED);
        return params.stream().map(param -> {
            Map<String, Object> resultMap = param;
            if (CollectionUtil.isNotEmpty(outVars)) {
                // 如果配置了结果显示字段，则按配置过滤结果和变量列表
                resultMap = new LinkedHashMap<>();
                for (Variable variable : outVars) {
                    String key = variable.getVarName();
                    resultMap.put(key, param.get(key));
                }
            }
            return ExecutionResult.builder()
                    .inputParams(param)
                    .results(List.of(resultMap))
                    .build();
        }).collect(Collectors.toList());
    }
}
